<?php
class Install_Controller_Index extends Install_Model_Controller {
	
	protected $_installer;
	
	public function __construct() {
		$this->_installer = Mag::object('Install_Model_Installer');
	}
	
	public function indexAction() {
		$this->_forward('database');
	}

	public function databaseAction() {
		$request = Mag::getRequest();
		if ($request->isPost()) {
			$validator = new Mag_Validator();
			$rules = array(
				array( 'field' => 'dbname', 'type' => FILTER_VALIDATE_EMPTY, 'label' => 'Database name' ),
				array( 'field' => 'uname',  'type' => FILTER_VALIDATE_EMPTY, 'label' => 'Username' ),
				array( 'field' => 'pwd',    'type' => FILTER_VALIDATE_REQUIRED, 'label' => 'Password' ),
				array( 'field' => 'dbhost', 'type' => FILTER_VALIDATE_EMPTY, 'label' => 'Database host' ),
				array( 'field' => 'prefix', 'type' => FILTER_VALIDATE_REQUIRED, 'label' => 'Prefix' )
			);

			$input = $request->getPost();
			if ($validator->run($input, $rules)) {
				// test connection
				$this->_installer->addData($input);
				$this->_redirect('*/*/run');	// go to next step
			} else {
				Mag::registry('form_data', $input);
				$this->_addErrors($validator->getErrors());
			}
		}
		$this->_loadLayout()->_renderLayout();
	}
	
	public function runAction() {
		$installer = $this->_installer;
		if ($installer->run()) {
			$this->getLayout()->addHandle('INSTALL_SUCCESS');
		} else {
			$this->getLayout()->addHandle('INSTALL_FAIL');
			$this->_addErrors(array($installer->getError()));
		}
		$this->_loadLayout()->_renderLayout();
	}

	protected function _addErrors($s) {
		Mag::singleton('Page_Model_Message_Collection')->addErrors($s);
	}
}